<template>

    <a-row style="border-bottom:1px solid var(--color-neutral-3)">
        <a-col :span="20">
            <a-button-group style="border-right: 1px solid var(--color-neutral-3)">
                <a-button @click="queryAll" :disabled="queryStatus==='query'">
                    <icon-caret-right style="color: rgb(var(--green-6))"/> &nbsp;执行全部
                </a-button>
                <a-button @click="querySelect" :disabled="queryStatus==='query'">
                    <icon-caret-right style="color: rgb(var(--green-6))"/> &nbsp;执行选中
                </a-button>
                <a-button @click="clear">
                    <icon-eraser style="color: rgb(var(--red-6))"/> &nbsp;全部清除
                </a-button>
                <!--                <a-button>
                                    <icon-menu-unfold style="color: rgb(var(&#45;&#45;orange-6))"/>&nbsp;格式化
                                </a-button>-->
                <a-button @click="showQueryHistory">
                    <icon-history style="color: rgb(var(--arcoblue-6))"/> &nbsp;历史记录
                </a-button>
                <a-button @click="exportData">
                    <icon-export style="color: rgb(var(--green-6))"/> &nbsp;导出结果
                </a-button>
            </a-button-group>
        </a-col>
        <a-col :span="4" style="text-align: right;padding: 4px 15px 0 0">
            <div v-if="queryStatus!=='init'">
                <a-tag v-if="queryStatus==='success'" color="green">
                    <template #icon>
                        <icon-check-circle/>
                    </template>
                    用时: {{ spendTime }}ms
                </a-tag>
                <a-tag v-if="queryStatus==='query'" color="arcoblue">
                    <template #icon>
                        <icon-sync spin/>
                    </template>
                    执行中
                </a-tag>
                <a-tag v-if="queryStatus==='error'" color="red">
                    <template #icon>
                        <icon-close-circle/>
                    </template>
                    执行失败
                </a-tag>
            </div>
        </a-col>
    </a-row>

    <a-split direction="vertical" :style="{height: 'calc(100% - 33px)'}">
        <template #first>
            <monaco-editor v-model="sql" language="sql" :hight-change="false" @editor-mounted="editorMounted"/>
        </template>
        <template #second>
            <a-typography v-if="queryStatus==='error'" style="margin: 20px">
                <a-typography-title :heading="6">
                    错误信息:
                </a-typography-title>
                <a-typography-paragraph>
                    {{ errorMessage }}
                </a-typography-paragraph>
            </a-typography>
            <a-table v-else-if="data.length>0" :columns="columns" :data="data" column-resizable :bordered="{cell:true}"
                     :scroll="{x: '100%',y: '100%'}" :scrollbar="true" :pagination="false" :size="'small'"></a-table>
        </template>
    </a-split>

    <query-history-modal ref="queryHistoryModal"></query-history-modal>

</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from "vue";
import {doQuery} from "../../scripts/mapper";
import {Message} from "@arco-design/web-vue";
import MonacoEditor from "../../components/Editor/MonacoEditor.vue";
import {getQueryHistoryList, saveQueryHistoryList} from "../../scripts/store";
import QueryHistoryModal from "./modal/QueryHistoryModal.vue";
import {exportToCsv} from "../../scripts/csv";

const queryHistoryModal = ref()
const sql = ref("");
const spendTime = ref(0);
const errorMessage = ref('');
const queryStatus = ref('init');

const columns:any[] = reactive([]);
const data:any[] = reactive([]);
const queryHistoryList:any[] = reactive([]);
let editorRef;

const editorMounted = (editor: any) => {
    editorRef = editor
}

onMounted(() => {
    getQueryHistoryList().then((result) => {
        queryHistoryList.splice(0, queryHistoryList.length)
        result.forEach(item => queryHistoryList.push(item))
    })
})

const clear = () => {
    queryStatus.value = 'init'
    sql.value = ''
    spendTime.value = 0
    errorMessage.value = ''
    columns.splice(0, columns.length);
    data.splice(0, data.length);
}

const queryAll = () => {
    if (!sql.value) {
        Message.error("请输入要执行的查询语句");
        return
    }
    query(sql.value);
}

const querySelect = () => {
    let selectSql = editorRef.getModel().getValueInRange(editorRef.getSelection())
    if (!selectSql) {
        Message.error("请选中要执行的查询语句");
        return
    }
    query(selectSql);
}

const query = (sqlValue) => {
    queryStatus.value = 'query'
    let startTime = new Date().getTime();
    doQuery(sqlValue).then((queryResult) => {
        if (queryResult.success && queryResult.data) {
            // Message.success("执行成功")
            queryStatus.value = 'success'
            spendTime.value = new Date().getTime() - startTime;
            columns.splice(0, columns.length);
            data.splice(0, data.length);
            queryResult.meta?.forEach((metaItem) => {
                columns.push({
                    title: metaItem.columnName,
                    dataIndex: metaItem.columnName,
                    width: 120
                })
            })
            queryResult.data?.forEach((dataItem: any) => {
                let dataObj = {};
                queryResult.meta?.forEach((metaItem, index) => {
                    dataObj[metaItem.columnName!] = dataItem[index]
                })
                data.push(dataObj)
            })
        } else {
            queryStatus.value = 'error'
            errorMessage.value = queryResult.message ? queryResult.message : ""
            //Message.error("执行失败" + (queryResult.message ? (": " + queryResult.message) : ""))
        }
    }).finally(() => {
        queryHistoryList.unshift({
          sql: sqlValue,
          time: new Date().toLocaleString(),
          status: queryStatus.value,
          spend: spendTime.value
        })
        if (queryHistoryList.length > 30) {
            queryHistoryList.splice(30, queryHistoryList.length - 30)
        }
        saveQueryHistoryList(queryHistoryList);
        if (queryStatus.value == 'query') {
            queryStatus.value = 'init'
        }
    })
}

const showQueryHistory = () => {
    if (queryHistoryList.length <= 0) {
        Message.info("暂无历史数据");
        return
    }
    queryHistoryModal.value.show(queryHistoryList)
}

const exportData = () => {
    if (data.length <= 0) {
        Message.info("无可导出数据");
        return
    }
    exportToCsv(data).then((success) => {
        if (success) {
            Message.success("导出成功")
        } else {
            Message.error("导出失败")
        }
    });

}


</script>

<style scoped>

</style>
